package com.jian.java;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Jiange
 * @create 2021-04-10-16:22
 */
public class JsonTest {
    /**
     * JSON是轻量级的数据交换格式相较于xml
     */
    @Test
    public void test1(){
        //javaBean和json的相互转换
        Person person = new Person("建哥", 10);
        Gson gson = new Gson();
        String s = gson.toJson(person);
        System.out.println(s);//{"name":"建哥","age":10}
        Person person1 = gson.fromJson(s, Person.class);
        System.out.println(person1);//Person{name='建哥', age=10}
    }

    @Test
    public void test2(){
        //List和json转换
        List<Person> list = new ArrayList<>();
        list.add(new Person("建哥",18));
        list.add(new Person("龙哥",18));
        list.add(new Person("来吧",18));

        Gson gson = new Gson();
        String s = gson.toJson(list);
        System.out.println(s);
        Object o = gson.fromJson(s, new PersonType().getType());
        System.out.println(o);
    }

    @Test
    public void test3(){
        //map和json
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("name","李子建");
        stringObjectHashMap.put("age",18);

        Gson gson = new Gson();
        String s = gson.toJson(stringObjectHashMap);
        System.out.println(s);
        Object o = gson.fromJson(s, new MapType().getType());
        System.out.println(o);
    }
}

class MapType extends TypeToken<HashMap<String,Object>>{

}

class PersonType extends TypeToken<List<Person>>{

}
